#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<netdb.h>
#include<string.h>
#include<stdlib.h>

#define HOSTLEN 256

int make_internet_address();

int make_dgram_server_socket(int portnum) {
    struct sockaddr_in saddr;
    int sock_id;

    sock_id = socket(PF_INET, SOCK_DGRAM, 0);
    if (sock_id == -1) {
        perror("Socket creation failed");
        return -1;
    }

    // ʹ�� INADDR_ANY �󶨵����п��õ�����ӿ
    memset(&saddr, 0, sizeof(saddr));
    saddr.sin_family = AF_INET;
    saddr.sin_addr.s_addr = htonl(INADDR_ANY);  // �󶨵���������ӿ�
    saddr.sin_port = htons(portnum);  // �󶨵�ָ���˿�

    // ���԰��׽���
    if (bind(sock_id, (struct sockaddr*)&saddr, sizeof(saddr)) != 0) {
        perror("Bind failed");
        return -1;
    }


    return sock_id;
}


int make_dgram_client_socket() {
	return socket(PF_INET, SOCK_DGRAM, 0);
}

int make_internet_address(char* hostname, int port, struct sockaddr_in* addrp) {
    struct addrinfo hints, * res;
    int status;

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET; // IPv4
    hints.ai_socktype = SOCK_DGRAM;

    status = getaddrinfo(hostname, NULL, &hints, &res);
    if (status != 0) {
        return -1;  // Error handling
    }
    memcpy(&addrp->sin_addr, &((struct sockaddr_in*)res->ai_addr)->sin_addr, sizeof(struct in_addr));
    addrp->sin_port = htons(port);
    freeaddrinfo(res);
    return 0;

}

int get_internet_address(char* host, int len, int* portp, struct sockaddr_in* addrp) {
	strncpy(host, inet_ntoa(addrp->sin_addr), len);
	*portp = ntohs(addrp->sin_port);
	return 0;
}